package com.myadapter;

import java.util.List;

import com.unit4science.R;

import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

/**
 * Tao ra ListAdapter co kha nang cuon tron
 * @author long
 *
 */
public class MyListAdapter extends ArrayAdapter<String>{

	private final int MAX_LENGTH = 1000;
	private int layoutResourceId;
	private List<String> items;
	
	/**
	 * 
	 * @param context
	 * @param layoutResourceId
	 * @param items
	 */
	public MyListAdapter(Context context, int layoutResourceId, List<String> items) {
		super(context, layoutResourceId, items);
		this.layoutResourceId = layoutResourceId;
		this.items = items;
	}
	
	/**
	 * @return convertView : tra ve mot TextView la mot row trong list
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		position = getTruePosition(position);
		if(convertView == null) {
			LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(layoutResourceId, parent, false);
		}
		String i = items.get(position);
		if(i != null) {
			TextView textView = (TextView) convertView.findViewById(R.id.item);
			textView.setText(Html.fromHtml(i));
		}
		
		return convertView;
	}
	
	@Override
	public int getCount() {
		return MAX_LENGTH;
	}
	
	@Override
	public String getItem(int position) {
		position = getTruePosition(position);
		return items.get(position);
	}
	
	@Override
	public long getItemId(int position) {
		position = getTruePosition(position);
		return position;
	}
	
	/**
	 * 
	 * @param position : vi tri trong mang [0..Integer.MAXVALUE-1]
	 * @return position : vi tri trong mang [0..items.size()-1]
	 */
	public int getTruePosition(int position) {
		if(position >= items.size()) {
			position = position % items.size();
		}
		return position;
	}
}